package cn.xpride.framework.task;

import cn.xpride.framework.http.SmartHttpApplication;
import cn.xpride.framework.http.SmartHttpContext;
import cn.xpride.framework.utils.FileUtil;
import cn.xpride.framework.utils.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
class TaskBizJob {

    private static final AtomicInteger COUNT =  new AtomicInteger(0);

    void monitor() {
        try {
            doJob();
        }catch (Exception e){
            log.error("处理任务失败,暂停任务",e);
            int count = COUNT.incrementAndGet();
            if(count > 3){
                COUNT.set(0);
                TaskRunnerContext.stop();
            }
        }
    }

    private void doJob() throws Exception{
        File srFile = new File(SmartHttpContext.getClassDir(),"json/swagger-resources");
        String r = HttpUtil.sendGet(SmartHttpApplication.getPropValue("res.url"));
        JSONArray array = JSONArray.parseArray(r);
        log.info("完成:swagger-resources同步");
        FileUtil.writeFileString(srFile.getAbsolutePath(),r);
        for (int i = 0; i < array.size(); i++) {
            JSONObject json = array.getJSONObject(i);
            String location = json.getString("location");
            String res = HttpUtil.sendGet(SmartHttpApplication.getPropValue("res.url").replaceAll("/swagger-resources",location));
            if(null != JSONObject.parseObject(res).getString("host")){
                File jsonFile = new File(SmartHttpContext.getClassDir(),"json" + location);
                FileUtil.writeFileString(jsonFile.getAbsolutePath(),res);
                log.info("完成:{}同步",location);
            }
        }
    }

}
